package cn.flant.io.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class BytesMessageHandler extends MessageHandler {
	private DatagramSocket socket;

	@Override
	public void onInit(DatagramSocket socket) throws IOException {
		this.socket = socket;
	}

	@Override
	public Object readMessage(byte[] bytes, int offset, int length) throws IOException {
		byte[] newBytes = new byte[length];
		System.arraycopy(bytes, offset, newBytes, 0, length);
		return newBytes;
	}

	@Override
	public void sendMessage(InetAddress addr, int port, Object message) throws IOException {
		if (message == null) {
			return;
		}
		byte[] bytes = (byte[]) message;
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length, addr, port);
		socket.send(packet);
	}

	@Override
	public void onClosed() {
	}
}
